package coreUtils

import (
	"fmt"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/xiaoqidun/qqwry"
)

func InitChunZhenIp() {
	_ = qqwry.LoadFile("./config_file/qqwry.dat")
}

func GetLocationByIp(ip string) (location *qqwry.Location, err error) {
	location = new(qqwry.Location)

	// 从内存或缓存查询IP
	defer func() {
		if r := recover(); r != nil {
			// 将 panic 转换为 error 返回
			err = fmt.Errorf("panic occurred: %v", r)
		}
	}()

	location, err = qqwry.QueryIP(ip)
	return location, err
}

// GetClientIP 获取用户真实 IP
func GetClientIP(c *gin.Context) string {
	// 优先从 X-Real-IP 获取
	ip := c.Request.Header.Get("X-Real-IP")
	if ip != "" {
		return ip
	}

	// 其次从 X-Forwarded-For 获取（第一个IP是用户真实IP）
	xff := c.Request.Header.Get("X-Forwarded-For")
	if xff != "" {
		ips := strings.Split(xff, ",")
		return strings.TrimSpace(ips[0])
	}

	// 最后 fallback 到直接连接IP
	return c.ClientIP()
}
